﻿/*
    This software is licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

    Copyright (C) 2010 Daniel Deptford (redmercury@gmail.com)
 
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:

        The above copyright notice and this permission notice shall be included in
        all copies or substantial portions of the Software.

        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
        THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;

namespace COLLADASharp
{
    public class NodeProperty
    {
        private NodeProperty(string propertyName, Type propertyType, object defaultProperty)
        {
            PropertyName = propertyName;
            PropertyType = propertyType;
            Default = defaultProperty;
        }

        static NodeProperty()
        {
            // Register all of the types in this assembly that have the [DAEClass] attribute
            Assembly thisAssembly = Assembly.GetExecutingAssembly();
            foreach (var type in thisAssembly.GetTypes())
            {
                if (!type.IsAbstract)
                {
                    DAEClassAttribute classAttribute = type.GetCustomAttributes(typeof(DAEClassAttribute), false).FirstOrDefault() as DAEClassAttribute;
                    if (classAttribute != null)
                    {
                        InitializeForClass(type);
                    }
                }
            }
        }

        public string PropertyName { get; private set; }
        public Type PropertyType { get; private set; }
        public object Default { get; private set; }

        internal class NodeTypeProperties
        {
            public Dictionary<string, NodeProperty> properties = new Dictionary<string, NodeProperty>(StringComparer.OrdinalIgnoreCase);
        }

        private static Dictionary<Type, NodeTypeProperties> classes = new Dictionary<Type, NodeTypeProperties>();

        public static NodeProperty Register(string name, Type propertyType, Type ownerType)
        {
            return Register(name, propertyType, ownerType, null);
        }

        public static NodeProperty Register(string name, Type propertyType, Type ownerType, object defaultProperty)
        {
            Debug.Assert(defaultProperty == null || propertyType.IsInstanceOfType(defaultProperty));

            NodeTypeProperties classProperties = null;
            if (!classes.TryGetValue(ownerType, out classProperties))
            {
                classProperties = new NodeTypeProperties();
                classes.Add(ownerType, classProperties);
            }

            if (classProperties.properties.ContainsKey(name))
                throw new ArgumentException("Property already registered.");

            NodeProperty nodeProperty = new NodeProperty(name, propertyType, defaultProperty);
            classProperties.properties.Add(name, nodeProperty);

            return nodeProperty;
        }

        internal static NodeTypeProperties GetClassProperties(Type type)
        {
            NodeTypeProperties properties = null;
            classes.TryGetValue(type, out properties);
            return properties;
        }

        internal static void InitializeForClass(Type type)
        {
            if (classes.ContainsKey(type))
            {
                return;
            }


            List<FieldInfo> allFields = new List<FieldInfo>();

            for (Type t = type; t != null; t = t.BaseType)
            {
                allFields.AddRange(t.GetFields(BindingFlags.Static | BindingFlags.NonPublic));
            }

            foreach (var field in allFields)
            {
                if (field.FieldType == typeof(NodeProperty))
                {
                    DAENodePropertyAttribute nodePropertyAttr = field.GetCustomAttributes(typeof(DAENodePropertyAttribute), false).FirstOrDefault() as DAENodePropertyAttribute;
                    if (nodePropertyAttr != null)
                    {
                        NodeProperty nodeProperty = field.GetValue(null) as NodeProperty;
                        if (nodeProperty != null)
                        {
                            continue;
                        }

                        PropertyInfo typePropertyAccessor = type.GetProperty(nodePropertyAttr.PropertyName);
                        if (typePropertyAccessor == null)
                        {
                            throw new DAEException(string.Format("{0} does not have a property named {1}", type.Name, nodePropertyAttr.PropertyName));
                        }

                        if (typePropertyAccessor.PropertyType != nodePropertyAttr.PropertyType)
                        {
                            throw new DAEException(string.Format("Property {0}.{1} does not match [DAENodeProperty] with type {2}", type.Name, typePropertyAccessor, nodePropertyAttr.PropertyType.Name));
                        }
                
                        nodeProperty = NodeProperty.Register(nodePropertyAttr.PropertyName, nodePropertyAttr.PropertyType, type, nodePropertyAttr.DefaultValue);
                        field.SetValue(null, nodeProperty);
                    }
                }
            }
        }
    }
}
